﻿using System;
using System.Collections.Generic;
using System.Data;
using SmartMenu.Classes;
using SmartMenu.Providers;
using visinia.SmartEngine.Cache;

namespace SmartMenu.Controllers
{
    public class MenuController
    {
        public static List<MenuInfo> GetMenus()
        {
            string key = "menusAll";
            List<MenuInfo> menus = (List<MenuInfo>)DataCache.GetCache(key);
            if (menus == null)
            {
                menus = FillMenus(SmartMenuDataProvider.Provider.GetMenus());
                DataCache.SetCache(key, menus, new TimeSpan(0, 30, 0));
            }
            return menus;
        }

        public static MenuInfo GetMenu(int MenuId)
        {
            return GetMenus().Find(p => p.MenuId == MenuId);
        }

        public static int AddMenu(MenuInfo menu)
        {
            IDataReader dr = SmartMenuDataProvider.Provider.AddMenu(menu.Name);
            int index = 0;
            while (dr.Read())
            {
                if (dr[0] != Convert.DBNull)
                    index = (int)dr[0];
            }
            DataCache.DeleteCacheMultiple("menusAll");
            dr.Close();
            return index;
        }

        public static void UpdateMenu(MenuInfo menu)
        {
            SmartMenuDataProvider.Provider.UpdateMenu(menu.MenuId, menu.Name);
            DataCache.DeleteCacheMultiple("menusAll");
        }

        public static void DeleteMenu(int menuId)
        {
            SmartMenuDataProvider.Provider.DeleteMenu(menuId);
            DataCache.DeleteCacheMultiple("menusAll");
        }

        #region PRIVATE METHODS
        private static List<MenuInfo> FillMenus(IDataReader dr)
        {
            List<MenuInfo> list = new List<MenuInfo>();
            while (dr.Read())
            {
                list.Add(ActualRead(dr));
            }
            dr.Close();
            return list;
        }

        private static MenuInfo ActualRead(IDataReader dr)
        {
            MenuInfo menu = new MenuInfo();
            if (dr["MenuId"] != Convert.DBNull)
                menu.MenuId = (int)dr["MenuId"];
            if (dr["Name"] != Convert.DBNull)
                menu.Name = (string)dr["Name"];
            return menu;
        }
        #endregion
    }

}
